package com.scqkxx.gamebox.activity.myself;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.ProgressCallback;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
//import com.luck.picture.lib.PictureSelector;
//import com.luck.picture.lib.config.PictureConfig;
//import com.luck.picture.lib.config.PictureMimeType;
//import com.luck.picture.lib.entity.LocalMedia;
import com.scqkxx.gamebox.R;
import com.scqkxx.gamebox.activity.activities.utils.GlideUtils;
import com.scqkxx.gamebox.activity.activities.view.TitleView;
import com.scqkxx.gamebox.activity.myself.spaceUtils.SpaceUtils;
import com.scqkxx.gamebox.bean.EvenBusBean;
import com.scqkxx.gamebox.databinding.ActivityMyselfInforBinding;
import com.scqkxx.gamebox.utils.DialogUtils;
import com.scqkzqtz.base.base.BaseActivity;
import com.scqkzqtz.base.library.utils.ToastUtils;
//import com.scqkzqtz.takepictrue.TakePictrueUiils;
import com.wildma.pictureselector.PictureSelector;

import org.greenrobot.eventbus.EventBus;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 个人信息  创建空间
 * Created by hef on 2018/8/13.
 */

public class MyselfInforActivity extends BaseActivity<ActivityMyselfInforBinding> {
    private String photoUrl = ""; //选择的图片地址
    private boolean isSwitch = false;
    private int spaceState = 0;
    private int belongGroupId;

    @Override
    public int setLayoutId() {
        return R.layout.activity_myself_infor;
    }

    @Override
    public void init() {
        spaceState = getIntent().getIntExtra("spaceState", 0);
        if (spaceState == 1) {
            //空间新增
            belongGroupId = getIntent().getIntExtra("belongGroupId" , 0);
            binding.tvTitleView.getTv_name().setText("新建空间");
            binding.postionsLin.setVisibility(View.GONE);
        } else if (spaceState == 2) {
            //空间修改
            binding.tvTitleView.getTv_name().setText("编辑空间");
            binding.postionsLin.setVisibility(View.GONE);
            String spaceName = getIntent().getStringExtra("spaceName");
            String imageUrl = getIntent().getStringExtra("imageUrl");
            belongGroupId = getIntent().getIntExtra("belongGroupId" , 0);
            photoUrl = imageUrl;
            binding.etPhoneNumber.setText(spaceName);
            if (!TextUtils.isEmpty(imageUrl)) {
                GlideUtils.loadImage(this, imageUrl, binding.photo);
            }
        } else if (spaceState == 3) {
            //位置新增
            binding.etPhoneNumber.setHint("请输入位置名称");
            binding.tvTitleView.getTv_name().setText("新建位置");
            binding.postionsLin.setVisibility(View.VISIBLE);
            String spaceName = getIntent().getStringExtra("spaceName");
            belongGroupId = getIntent().getIntExtra("spaceId"  ,0);
            binding.spaceName.setText(spaceName);
        } else if (spaceState == 4) {
            //位置修改
            binding.etPhoneNumber.setHint("请输入位置名称");
            binding.tvTitleView.getTv_name().setText("编辑位置");
            binding.postionsLin.setVisibility(View.VISIBLE);
            String spaceName = getIntent().getStringExtra("spaceName");
            binding.tvSubordinate.setText("所属空间");
            binding.spaceName.setText(spaceName);
            String goodsName = getIntent().getStringExtra("goodsName");
            String imageUrl = getIntent().getStringExtra("imageUrl");
            belongGroupId = getIntent().getIntExtra("belongGroupId" , 0 );
            photoUrl = imageUrl;
            binding.etPhoneNumber.setText(goodsName);
            if (!TextUtils.isEmpty(imageUrl)) {
                GlideUtils.loadImage(this, imageUrl, binding.photo);
            }
        } else  if (spaceState == 5){
            //物品新增
            belongGroupId = Integer.valueOf(getIntent().getStringExtra("spaceId"));
            binding.etPhoneNumber.setHint("请输入物品名称");
            binding.tvTitleView.getTv_name().setText("新建物品");
            binding.postionsLin.setVisibility(View.VISIBLE);
            String goodsName = getIntent().getStringExtra("goodsName");
            binding.tvSubordinate.setText("所属位置");
            binding.spaceName.setText(goodsName);
            binding.tvRemarks.setVisibility(View.VISIBLE);
        }else if (spaceState == 6){
            //物品编辑
            binding.etPhoneNumber.setHint("请输入物品名称");
            binding.tvTitleView.getTv_name().setText("编辑物品");
            binding.postionsLin.setVisibility(View.VISIBLE);
            String goodsName = getIntent().getStringExtra("goodsName");
            String spaceName = getIntent().getStringExtra("spaceName");
            String imageUrl = getIntent().getStringExtra("imageUrl");
            boolean isPblic = getIntent().getBooleanExtra("isPblic"  ,false);
            belongGroupId = Integer.valueOf(getIntent().getStringExtra("objectId"));
            String note  =getIntent().getStringExtra("note");
            photoUrl = imageUrl;
            binding.tvSubordinate.setText("所属位置");
            binding.spaceName.setText(spaceName);
            binding.etPhoneNumber.setText(goodsName);
            binding.tvRemarks.setVisibility(View.VISIBLE);
            binding.tvEditext.setText(note);
            binding.isSwitch.setChecked(isPblic);
            if (!TextUtils.isEmpty(imageUrl)) {
                GlideUtils.loadImage(this, imageUrl, binding.photo);
            }
        }
        if (!TextUtils.isEmpty(binding.etPhoneNumber.getText().toString().trim())){
            binding.etPhoneNumber.setSelection(binding.etPhoneNumber.getText().toString().length());
        }

        binding.tvTitleView.setOnTitleClickListener(mTitleType -> {
            if (TitleView.CLICK_BACK == mTitleType) {
                finish();
            }
        });

        binding.photo.setOnClickListener(view -> {
            PictureSelector
                    .create(MyselfInforActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                    .selectPicture(false, 200, 200, 1, 1);
//            new TakePictrueUiils()
//                    .setClip(false)
//                    .setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark))
//                    .setOnSelectTakePictrueListener((bitmap, pictrueFlie) -> commitPhoto(pictrueFlie))
//                    .start(MyselfInforActivity.this);
        });

        binding.tvConfirm.setOnClickListener(v -> {
            String spaceName = binding.etPhoneNumber.getText().toString().trim();
            String mRemarks = binding.tvEditext.getText().toString().trim();
            if (TextUtils.isEmpty(spaceName)) {
                ToastUtils.showShortToast(MyselfInforActivity.this, "空间名字不能为空");
                return;
            }
            if ( spaceName.length() > 20 ) {
                ToastUtils.showShortToast(MyselfInforActivity.this, "空间名字最多只能为20个字");
                return;
            }
            if (TextUtils.isEmpty(photoUrl)) {
                ToastUtils.showShortToast(MyselfInforActivity.this, "请选择空间图片");
                return;
            }
            Log.e("TAG" , belongGroupId+"");
            //新建空间  位置   物品
            SpaceUtils.insterSpaceAndGoods(spaceState,MyselfInforActivity.this,spaceName,isSwitch,photoUrl,belongGroupId ,mRemarks);
        });
        binding.isSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> MyselfInforActivity.this.isSwitch = isChecked);
    }


//    public void showDialog(){
//        AlertDialog.Builder builder=new AlertDialog.Builder(this)
//                .setTitle("选择图片：")
//                //设置两个item
//                .setItems(new String[]{"相机","图库"}, (dialog, which) -> {
//                    switch (which) {
//                        case 0:
//                            break;
//                        case 1:
//                            break;
//                        default:
//                            break;
//                    }
//
//                });
//        builder.create().show();
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                String picturePath = data.getStringExtra(PictureSelector.PICTURE_PATH);
                commitPhoto(picturePath);
            }
        }
    }

    /**
     * 设置头像
     *
     * @param imageUrl
     */
    private void setImageUrl(String imageUrl) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.icon_user_header_default)
                .error(R.mipmap.icon_user_header_default);
        Glide.with(this).load(imageUrl).apply(options).into(binding.photo);
    }

    /**
     * 上传头像
     *
     * @param imagePath
     */
    private void commitPhoto(final String imagePath) {
        DialogUtils.showDialog(this);
        try {
            final AVFile file = AVFile.withAbsoluteLocalPath("LeanCloud.png", imagePath);
            file.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (null == e) {
                        final String url = file.getUrl();
                        MyselfInforActivity.this.photoUrl = url;
                        setImageUrl(url);
                    } else {
                        ToastUtils.showShortToast(MyselfInforActivity.this, "图片上传失败..");
                    }
                    DialogUtils.dismiss();
                }
            }, new ProgressCallback() {
                @Override
                public void done(Integer integer) {
                    // 上传进度数据，integer 介于 0 和 100。
                    Log.d("LeanCloud_imagePath", String.valueOf(integer));//返回一个唯一的 Url 地址
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
